package service

import (
	"context"
	"github.com/shopspring/decimal"
	"insighttracking/common/enum"
	"insighttracking/query/dao"
	"insighttracking/query/model"
	"time"
)

type _spuStoreWeighRecordService struct{}

func (s _spuStoreWeighRecordService) CreateSpuStoreWeighRecordApi(ctx context.Context, enterpriseId, purchaseStoreDetailId, spuId int64, weight decimal.Decimal) error {
	if err := dao.SpuStoreWeighRecordEntity.WithContext(ctx).Create(&model.SpuStoreWeighRecordEntity{
		EnterpriseID:          enterpriseId,
		SpuID:                 spuId,
		Weight:                weight,
		PurchaseStoreDetailID: purchaseStoreDetailId,
	}); err != nil {
		return err
	}
	return nil
}

func (s _spuStoreWeighRecordService) DeleteSpuStoreWeighRecordApi(ctx context.Context, id int64) error {
	if _, err := dao.SpuStoreWeighRecordEntity.WithContext(ctx).Where(dao.SpuStoreWeighRecordEntity.ID.Eq(id)).Delete(); err != nil {
		return err
	}
	return nil
}

func (s _spuStoreWeighRecordService) GetSpuStoreWeighRecordByIdApi(ctx context.Context, id int64) (*model.SpuStoreWeighRecordEntity, error) {
	return dao.SpuStoreWeighRecordEntity.WithContext(ctx).Where(
		dao.SpuStoreWeighRecordEntity.ID.Eq(id),
	).First()
}

func (s _spuStoreWeighRecordService) GetSpuStoreWeighRecordApi(ctx context.Context, enterpriseId int64, purchaseStoreDetailId, spuId int64) ([]*model.SpuStoreWeighRecordEntity, error) {
	return dao.SpuStoreWeighRecordEntity.WithContext(ctx).Where(
		dao.SpuStoreWeighRecordEntity.EnterpriseID.Eq(enterpriseId),
		dao.SpuStoreWeighRecordEntity.SpuID.Eq(spuId),
		dao.SpuStoreWeighRecordEntity.PurchaseStoreDetailID.Eq(purchaseStoreDetailId),
		dao.SpuStoreWeighRecordEntity.CreatedAt.DateFormat("%Y-%m-%d").Eq(time.Now().Format("2006-01-02")),
		dao.SpuStoreWeighRecordEntity.Status.Eq(enum.SpuStoreWeighRecordWait),
	).Or(
		dao.SpuStoreWeighRecordEntity.EnterpriseID.Eq(enterpriseId),
		dao.SpuStoreWeighRecordEntity.SpuID.Eq(spuId),
		dao.SpuStoreWeighRecordEntity.PurchaseStoreDetailID.Eq(purchaseStoreDetailId),
		dao.SpuStoreWeighRecordEntity.Status.Eq(enum.SpuStoreWeighRecord),
	).Find()
}

func (s _spuStoreWeighRecordService) ModifyStatusBySpuIdApi(ctx context.Context, tx *dao.QueryTx, enterpriseId int64, spuId int64) error {
	if _, err := tx.SpuStoreWeighRecordEntity.WithContext(ctx).Where(
		dao.SpuStoreWeighRecordEntity.EnterpriseID.Eq(enterpriseId),
		dao.SpuStoreWeighRecordEntity.SpuID.Eq(spuId),
	).UpdateSimple(dao.SpuStoreWeighRecordEntity.Status.Value(1)); err != nil {
		return err
	}
	return nil
}

var SpuStoreWeighRecordService = new(_spuStoreWeighRecordService)
